
from datetime import datetime
from django.shortcuts import render
from rest_framework.views import APIView
from .serializers import LoginSerializer, UserSerializer
from .authentications import generate_jwt
from rest_framework.response import Response
from rest_framework import  status
from rest_framework.permissions import IsAuthenticated
from .serializers import ResetPwdSerializer
from rest_framework.status import HTTP_400_BAD_REQUEST

class LoginView(APIView):
    def post(self, request):
        # 1.验证数据是否可用
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            user.last_login = datetime.now()
            user.save()

            # 生成JWT
            token = generate_jwt(user)
            # print({'token': token, 'user': UserSerializer(user).data})
            return Response({'token': token, 'user': UserSerializer(user).data})

        else:
            print(serializer.errors)
            # drf返回非200的状态码时，其错误参数名叫detail，所以这里我们也叫detail
            # detail = list(serializer.errors.values())[0][0]
            return Response({'detail': "参数验证失败！"}, status=status.HTTP_400_BAD_REQUEST)


class ResetPwdView(APIView):

    # request：是DRF封装的，rest_framework.request.Request
    # 这个对象是针对Django的HttpRequest对象进行了封装
    def post(self, request):

        serializer = ResetPwdSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            pwd1 = serializer.validated_data.get('pwd1')
            request.user.set_password(pwd1)
            request.user.save()
            return Response(status=status.HTTP_200_OK)

        else:
            detail = list(serializer.errors.values())[0][0]
            return Response({'datail': detail}, status=status.HTTP_400_BAD_REQUEST)

